package com.wanfajie.smsdistribute.main.fragment.template

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SearchView
import android.text.style.CharacterStyle
import android.text.style.ForegroundColorSpan
import android.view.*
import android.widget.Button
import android.widget.TextView
import com.wanfajie.smsdistribute.R
import com.wanfajie.smsdistribute.common.adapter.CheckedRecyclerAdapter
import com.wanfajie.smsdistribute.common.fragment.BaseFragment
import com.wanfajie.smsdistribute.db.bean.template.TemplateBean
import com.wanfajie.smsdistribute.db.quietInvoke
import com.wanfajie.smsdistribute.db.repository.impl.TemplateRepositoryImpl
import com.wanfajie.smsdistribute.ui.send_sms_bulk.SendSmsBulkActivity
import com.wanfajie.smsdistribute.ui.template_editor.SmsTemplateEditorActivity
import com.wanfajie.smsdistribute.util.confirm
import com.wanfajie.smsdistribute.util.highLight
import com.wanfajie.smsdistribute.util.toast
import java.sql.SQLException

class TemplateManageFragment: BaseFragment() {

    companion object {
        private const val TAG = "TemplateManageFragment"
        private const val REQUEST_NEW = 1
        private const val REQUEST_EDIT = 2
    }

    private lateinit var mActivity: Activity
    private lateinit var mContentView: View
    private lateinit var mTemplateRecycler: RecyclerView

    private val mHighLightFactory: () -> CharacterStyle by lazy {
        val ctx: Context = context ?: mActivity
        val color = ctx.resources.getColor(android.R.color.holo_red_light)

        val factory = {
            ForegroundColorSpan(color)
        }

        factory
    }
    private var mSearchView: SearchView? = null
    private var mKeyword: String = ""

    private var mLastEdit: TemplateBean? = null

    private val mAdapter by lazy {
        object : CheckedRecyclerAdapter<TemplateBean>(mActivity, emptyList(),
                R.layout.list_item_template, R.id.checkbox) {
            init {
                setItemCheckable(false)
                setOnLongClickListener(View.OnLongClickListener {
                    // TODO: ActionMode
                    true
                })
                setOnItemClickListener { _, it ->
                    if (!isItemCheckable())
                        SendSmsBulkActivity.startActivity(mActivity, it)
                }
            }
            override fun processViewHolder(p0: CheckedViewHolder, p1: TemplateBean) {
                p0.get<TextView>(R.id.template_title).text = highLight(p1.title, mKeyword, mHighLightFactory)
                p0.get<TextView>(R.id.template_content).text = highLight(p1.content, mKeyword, mHighLightFactory)

                val editBtn = p0.get<Button>(R.id.btn_edit)
                val delBtn = p0.get<Button>(R.id.btn_delete)
                if (editBtn.tag == null) {
                    editBtn.setOnClickListener {
                        val bean = it.tag as TemplateBean
                        val intent = Intent(mActivity, SmsTemplateEditorActivity::class.java)
                        intent.putExtra(SmsTemplateEditorActivity.EXTRA_TEMPLATE_ID, bean.id)
                        mLastEdit = bean
                        this@TemplateManageFragment.startActivityForResult(intent, REQUEST_EDIT)
                    }

                    delBtn.setOnClickListener {
                        val bean = it.tag as TemplateBean
                        val message = getString(R.string.confirm_delete_template, bean.title)

                        confirm(mActivity, R.string.delete, message, R.string.delete) { _, witch ->
                            if (witch != DialogInterface.BUTTON_POSITIVE) return@confirm
                            val success = quietInvoke(TAG, false, SQLException::class) {
                                bean.delete() > 0
                            }

                            if (success) {
                                remove(bean)
                                toast(strId = R.string.successfully_deleted)
                            } else {
                                toast(strId = R.string.delete_failure)
                            }
                        }
                    }
                }

                editBtn.tag = p1
                delBtn.tag = p1
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (!::mContentView.isInitialized) {
            mContentView = inflater.inflate(R.layout.fragment_template_manage, container, false)
            mTemplateRecycler = mContentView.findViewById(R.id.template_list)
            mTemplateRecycler.adapter = mAdapter
            val manager = LinearLayoutManager(mActivity)
            manager.orientation = OrientationHelper.VERTICAL
            mTemplateRecycler.layoutManager = manager
        }
        setHasOptionsMenu(true)

        return mContentView
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return when (item?.itemId) {
            R.id.create -> {
                val intent = Intent(mActivity, SmsTemplateEditorActivity::class.java)
                startActivityForResult(intent, REQUEST_NEW)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        when (requestCode) {
            REQUEST_NEW -> {
                if (resultCode != Activity.RESULT_OK) return
                val id = data?.getIntExtra(SmsTemplateEditorActivity.EXTRA_TEMPLATE_ID, -1) ?: return
                if (id == -1) return

                val bean = TemplateRepositoryImpl.get(id)
                if (bean == null) {
                    mAdapter.setItems(TemplateRepositoryImpl.queryAll())
                } else {
                    mAdapter.add(bean, 0)
                }
            }
            REQUEST_EDIT -> {
                mLastEdit?.let {
                    val index = mAdapter.indexOf(it)
                    val reloadBean = TemplateRepositoryImpl.get(it.id) ?: return
                    mAdapter.remove(it)
                    mAdapter.add(reloadBean, index)
                    mLastEdit = null
                }
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        inflater?.inflate(R.menu.menu_frag_template, menu)
        mSearchView = menu?.findItem(R.id.search)?.actionView as SearchView?
        mSearchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextChange(p0: String?): Boolean = false
            override fun onQueryTextSubmit(p0: String?): Boolean {
                mKeyword = p0 ?: ""
                searchTemplate()
                return true
            }
        })

        mSearchView?.setOnCloseListener {
            mKeyword = ""
            searchTemplate()
            false
        }

        mKeyword = ""
        searchTemplate()
    }

    private fun searchTemplate() {
        val templates = TemplateRepositoryImpl.queryKeyword(mKeyword)
        mAdapter.setItems(templates)
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        mActivity = activity!!
    }

    override fun onBackPressed(): Boolean {
        return when (mSearchView?.isIconified) {
            false -> {
                mSearchView?.isIconified = true
                true
            }
            else -> false
        }
    }
}